<?php

namespace common\logics;

use Yii;
use common\helpers\ArrayHelper;
use common\models\views\ViewSpecialDiscount;

/**
 * BrandController implements the CRUD actions for Brands model.
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class DiscountLogic extends \common\base\Model {

    public $items = null;

    public function __construct($config = []) {
        parent::__construct($config);
    }

    /**
     * 计算
     */
    public function reckon() {
        $goods = $this->items;

        $scopes = [];
        foreach ($goods as $key => $val) {
            //0商品
            $scopes['goods_ids'][] = $val['id'];
            //1店铺
            if (isset($val['shop_id'])) {
                $scopes['shop_ids'][] = $val['type_id'];
            }
            //2品牌
            if (isset($val['brand_id'])) {
                $scopes['brand_ids'][] = $val['brand_id'];
            }
            //3品类
            if (isset($val['type_id'])) {
                $scopes['type_ids'][] = $val['type_id'];
            }
            //4运费
            //5平台
        }
        //优惠活动
        $activity = ViewSpecialDiscount::findAvalid($scopes);

        foreach ($activity as $scope => $rules) {
            $goods = $this->reckonDiscount($scope, $rules, $goods);
        }

        return $goods;
    }

    public function averageDiscount($array, $cut) {
        $amount = array_sum($array);
        $dis = [];
        foreach ($array as $key => $vls) {
            $dis[$key] = round($vls * $cut / $amount, 1);
        }
        $damount = $cut - array_sum($dis);
        $dmax = max($dis);
        $mk = array_search($dmax, $dis);
        $dis[$mk] += $damount;
        foreach ($array as $key => $vls) {
            $array[$key] -= $dis[$key];
        }
        return $array;
    }

    public function reckonDiscount($scope, $specials, $goods) {
        $scopes = [
            'id' => 0,
            'shop_id' => 1,
            'brand_id' => 2,
            'type_id' => 3,
        ];
        $goodsSubTotal = ArrayHelper::map($goods, 'id', 'subtotal');

        $scopekey = array_search($scope, $scopes);

        if ($scopekey === false) {
            return $goods;
        }

        $tempGoods = [];
        $tempCount = [];
        foreach ($specials as $ruleid => $discont) {
            foreach ($goods as $key => $val) {
                if (!in_array($val[$scopekey], $discont['model_ids'])) {
                    continue;
                }
                $tempCount[$ruleid][] = $val[$scopekey];
                $tempGoods[$ruleid][$val['id']] = $val['subtotal'];
            }
        }

        $rules = $this->checkIntersect($tempCount);

        $tempArray = [];
        $goodsRuleAmount = [];
        $goodsRule = [];
        foreach ($tempGoods as $ruleid => $goodslist) {
            $discount = isset($specials[$ruleid]) ? $specials[$ruleid] : [];
            if (empty($discount)) {
                continue;
            }
            $amount = array_sum($goodslist);
            if ($amount < $discount['limit']) {
                continue;
            }
            $cut = $discount['discount'];
            if ($discount['radix'] > 0) {
                $cut = round($amount * (1 - $discount['discount'] / $discount['radix']));
            }
            $average = $this->averageDiscount($goodslist, $cut);

            if (in_array($ruleid, $rules)) {
                $subTotal = $goodsSubTotal;
                foreach ($average as $goodsid => $v) {
                    $subTotal[$goodsid] = $v;
                }
                $goodsRuleAmount[$ruleid] = array_sum($subTotal);
                $goodsRule[$ruleid] = $average;
            } else {
                foreach ($average as $goodsid => $v) {
                    $tempArray[$goodsid][] = $v;
                }
            }
        }

        if (!empty($goodsRuleAmount)) {
            $dmin = min($goodsRuleAmount);
            $ruleid = array_search($dmin, $goodsRuleAmount);
            $result = $goodsRule[$ruleid];
            foreach ($result as $key => $val) {
                $goods[$key]['subtotal'] = $val;
            }
        }

        if (!empty($tempArray)) {
            foreach ($tempArray as $key => $val) {
                $goods[$key]['subtotal'] = min($val);
            }
        }

        return $goods;
    }

    public function checkIntersect($array) {
        $rules = [];
        foreach ($array as $key => $vls) {
            $temp = $array;
            unset($temp[$key]);
            foreach ($temp as $tk => $tv) {
                if (in_array($key, $rules)) {
                    continue;
                }
                $t = array_intersect($vls, $tv);
                if (!empty($t)) {
                    $rules[] = $key;
                }
            }
        }
        return $rules;
    }

}
